package com.jojo.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jojo.constant.ProductConstants;
import com.jojo.domain.ProdPropValue;
import com.jojo.exception.BusinessException;
import com.jojo.mapper.ProdPropValueMapper;
import com.jojo.service.ProdPropValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jojo.domain.ProdProp;
import com.jojo.mapper.ProdPropMapper;
import com.jojo.service.ProdPropService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@CacheConfig(cacheNames = "com.jojo.service.impl.ProdPropServiceImpl")
public class ProdPropServiceImpl extends ServiceImpl<ProdPropMapper, ProdProp> implements ProdPropService{

    @Autowired
    private ProdPropMapper prodPropMapper;

    @Autowired
    private ProdPropValueMapper prodPropValueMapper;

    @Autowired
    private ProdPropValueService prodPropValueService;

    @Override
    public Page<ProdProp> queryProdPage(Long current, Long size, String propName) {
        //多条件分页查询商品属性
        Page<ProdProp> page = new Page<>(current,size);
        page = prodPropMapper.selectPage(page,new LambdaQueryWrapper<ProdProp>()
                .like(StringUtils.hasText(propName),ProdProp::getPropName,propName)
        );
        //从分页对象中获取属性记录
        List<ProdProp> prodPropList = page.getRecords();
        if (CollectionUtil.isEmpty(prodPropList) || prodPropList.size()==0) {
            //说明属性对象没有值
            return page;
        }
        //从属性对象集合中获取属性id集合
        List<Long> propIdList = prodPropList.stream().map(ProdProp::getPropId).collect(Collectors.toList());
        //属性id集合查询属性值对象集合
        List<ProdPropValue> prodPropValuesList = prodPropValueMapper.selectList(new LambdaQueryWrapper<ProdPropValue>()
                .in(ProdPropValue::getPropId, propIdList)
        );

        prodPropList.forEach(prodProp ->{
            //从属性值对象集合中过滤出与当前属性对象的属性id一致的属性对象集合
            List<ProdPropValue> list = prodPropValuesList.stream()
                    .filter(prodPropValue -> prodPropValue.getPropId().equals(prodProp.getPropId()))
                    .collect(Collectors.toList());
            prodProp.setProdPropValues(list);
        });
        return page;
    }

    /**
     * 新增商品规格      #此处门店id#
     *
     * 1. 新增商品属性对象 ->属性id
     * 2. 批量添加商品属性值对象
     */
    // TODO
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = ProductConstants.PROD_PROP_KEY)
    public Boolean saveProdSpec(ProdProp prodProp) {
        //新增商品属性对象
        prodProp.setShopId(1L);
        prodProp.setRule(2);
        int i = prodPropMapper.insert(prodProp);
        if (i>0) {
            //添加商品属性对象与属性值的记录
            //获取商品属性值集合
            List<ProdPropValue> propValueList = prodProp.getProdPropValues();
            //判断是否有值
            if (CollectionUtil.isNotEmpty(propValueList) && propValueList.size()!=0) {
                propValueList.forEach(prodPropValue -> prodPropValue.setPropId(prodProp.getPropId()));
                //批量添加属性值对象集合
                prodPropValueService.saveBatch(propValueList);
            }
        }
        return i>0;
    }


    /**
     * @param prodProp 商品属性对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = ProductConstants.PROD_PROP_KEY)
    public Boolean modifyPropSpec(ProdProp prodProp) {
        if (prodProp.getProdPropValues().size() == 0)
            throw new BusinessException("属性值不能为空");
        //获取原属性值对象id集合
        List<ProdPropValue> OriginalList = prodPropValueMapper.selectList(new LambdaQueryWrapper<ProdPropValue>()
                .eq(ProdPropValue::getPropId, prodProp.getPropId())
        );
        List<Long> OriginalValueIds = OriginalList.stream().map(ProdPropValue::getValueId).collect(Collectors.toList());
        //获取新的属性值对象id集合
        List<ProdPropValue> afterProdPropValues = prodProp.getProdPropValues();
        List<Long> afterValueIds = afterProdPropValues.stream().map(ProdPropValue::getValueId).collect(Collectors.toList());
        //获取被删除的属性值对象id集合
        afterValueIds.removeAll(Collections.singleton(null));
        OriginalValueIds.removeAll(afterValueIds);
        //根据id删除属性值对象
        if (CollectionUtil.isNotEmpty(OriginalValueIds) && OriginalValueIds.size() != 0)
            prodPropValueMapper.deleteBatchIds(OriginalValueIds);

        afterProdPropValues.forEach(propValue -> {
            if (ObjectUtil.isEmpty(propValue.getPropId()))
                propValue.setPropId(prodProp.getPropId());
        });

        boolean flag = prodPropValueService.saveOrUpdateBatch(afterProdPropValues);

        if (flag) {
            List<ProdPropValue> newList = prodPropValueMapper.selectList(new LambdaQueryWrapper<ProdPropValue>()
                    .eq(ProdPropValue::getPropId, prodProp.getPropId())
            );
            prodProp.setProdPropValues(newList);
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = ProductConstants.PROD_PROP_KEY)
    public Boolean removePropSpecByPropId(Long propId) {
        //根据属性标识删除属性值
        prodPropValueMapper.delete(new LambdaQueryWrapper<ProdPropValue>()
                .eq(ProdPropValue::getPropId,propId)
        );
        //删除属性对象
        return prodPropMapper.deleteById(propId) > 0;
    }

    @Override
    @Cacheable(key = ProductConstants.PROD_PROP_KEY)
    public List<ProdProp> queryProdPropList() {
        return prodPropMapper.selectList(null);
    }
}
